/*
 * @Description: 学生管理相关API
 * @Author: charles
 * @Date: 2023-06-10 10:00:00
 * @LastEditors: charles
 * @LastEditTime: 2023-06-10 10:00:00
 */
import { get, post, put, del } from '@/utils/request'

// 本地模拟数据 - 当后端接口不可用时使用
const mockStudentList = [
  {
    id: '202101',
    name: '崔胜威',
    gender: 'M',
    stuNo: '01',
    birth: '1995-08-08',
    telephone: '',
    grade: '2021',
    major: '计算机科学与技术',
    className: '计科2101',
    email: 'cuishengwei@example.com',
    courseCount: 3,
    clazzId: null
  },
  {
    id: '202102',
    name: '尹争汉',
    gender: 'M',
    stuNo: '02',
    birth: '1995-10-04',
    telephone: '',
    grade: '2021',
    major: '软件工程',
    className: '软工2101',
    email: 'yinzhenghan@example.com',
    courseCount: 2,
    clazzId: null
  },
  {
    id: '202103',
    name: '洪知秀',
    gender: 'M',
    stuNo: '03',
    birth: '1995-12-30',
    telephone: '',
    grade: '2021',
    major: '网络工程',
    className: '网工2101',
    email: 'hongzhixiu@example.com',
    courseCount: 4,
    clazzId: null
  },
  {
    id: '202104',
    name: '文俊辉',
    gender: 'M',
    stuNo: '04',
    birth: '1996-06-10',
    telephone: '',
    grade: '2021',
    major: '计算机科学与技术',
    className: '计科2102',
    email: 'wenjunhui@example.com',
    courseCount: 3,
    clazzId: null
  },
  {
    id: '202105',
    name: '权顺荣',
    gender: 'M',
    stuNo: '05',
    birth: '1996-06-15',
    telephone: '',
    grade: '2021',
    major: '软件工程',
    className: '软工2102',
    email: 'quanshunrong@example.com',
    courseCount: 2,
    clazzId: null
  },
  {
    id: '202106',
    name: '全圆佑',
    gender: 'M',
    stuNo: '06',
    birth: '1996-07-17',
    telephone: '',
    grade: '2021',
    major: '人工智能',
    className: '人工2101',
    email: 'quanyuanyou@example.com',
    courseCount: 3,
    clazzId: null
  },
  {
    id: '202107',
    name: '李知勋',
    gender: 'M',
    stuNo: '07',
    birth: '1996-11-22',
    telephone: '',
    grade: '2021',
    major: '数据科学与大数据技术',
    className: '数科2101',
    email: 'lizhixun@example.com',
    courseCount: 5,
    clazzId: null
  },
  {
    id: '202108',
    name: '徐明浩',
    gender: 'M',
    stuNo: '08',
    birth: '1997-11-07',
    telephone: '',
    grade: '2022',
    major: '计算机科学与技术',
    className: '计科2201',
    email: 'xuminghao@example.com',
    courseCount: 4,
    clazzId: null
  },
  {
    id: '202109',
    name: '金珉奎',
    gender: 'M',
    stuNo: '09',
    birth: '1997-04-06',
    telephone: '',
    grade: '2022',
    major: '软件工程',
    className: '软工2201',
    email: 'jinmingui@example.com',
    courseCount: 3,
    clazzId: null
  },
  {
    id: '202110',
    name: '李硕珉',
    gender: 'M',
    stuNo: '10',
    birth: '1997-02-18',
    telephone: '',
    grade: '2022',
    major: '网络空间安全',
    className: '网安2201',
    email: 'lishuomin@example.com',
    courseCount: 2,
    clazzId: null
  },
  {
    id: '202111',
    name: '夫胜宽',
    gender: 'M',
    stuNo: '11',
    birth: '1998-01-16',
    telephone: '',
    grade: '2022',
    major: '计算机科学与技术',
    className: '计科2202',
    email: 'fushengkuan@example.com',
    courseCount: 3,
    clazzId: null
  },
  {
    id: '202112',
    name: '崔韩率',
    gender: 'M',
    stuNo: '12',
    birth: '1998-02-18',
    telephone: '',
    grade: '2022',
    major: '软件工程',
    className: '软工2202',
    email: 'cuihanlv@example.com',
    courseCount: 4,
    clazzId: null
  },
  {
    id: '202113',
    name: '李灿',
    gender: 'M',
    stuNo: '13',
    birth: '1999-02-11',
    telephone: '',
    grade: '2022',
    major: '数据科学与大数据技术',
    className: '数科2201',
    email: 'lican@example.com',
    courseCount: 2,
    clazzId: null
  }
]

// 模拟课程数据
const mockCourseList = [
  {
    courseId: 'CS101',
    courseName: '计算机科学导论',
    credit: 3,
    teacherName: '张教授',
    selectedCount: 28,
    capacity: 35,
    status: '可选'
  },
  {
    courseId: 'CS201',
    courseName: '数据结构',
    credit: 4,
    teacherName: '王教授',
    selectedCount: 30,
    capacity: 40,
    status: '可选'
  },
  {
    courseId: 'CS301',
    courseName: '操作系统',
    credit: 3,
    teacherName: '李教授',
    selectedCount: 25,
    capacity: 35,
    status: '可选'
  },
  {
    courseId: 'CS401',
    courseName: '计算机网络',
    credit: 3,
    teacherName: '赵教授',
    selectedCount: 20,
    capacity: 30,
    status: '可选'
  },
  {
    courseId: 'MA202',
    courseName: '高等数学',
    credit: 4,
    teacherName: '陈教授',
    selectedCount: 45,
    capacity: 50,
    status: '可选'
  },
  {
    courseId: 'EN303',
    courseName: '英语写作',
    credit: 2,
    teacherName: '刘老师',
    selectedCount: 30,
    capacity: 30,
    status: '已满'
  },
  {
    courseId: 'AR404',
    courseName: '艺术设计',
    credit: 2,
    teacherName: '黄老师',
    selectedCount: 25,
    capacity: 30,
    status: '可选'
  },
  {
    courseId: 'PH505',
    courseName: '物理学',
    credit: 3,
    teacherName: '吴教授',
    selectedCount: 42,
    capacity: 45,
    status: '可选'
  }
]

// 模拟已选课程数据
const mockSelectedCourses = {
  '202101': [
    {
      courseId: 'CS101',
      courseName: '计算机科学导论',
      credit: 3,
      teacherName: '张教授',
      selectTime: '2023-09-01 10:30:45'
    },
    {
      courseId: 'MA202',
      courseName: '高等数学',
      credit: 4,
      teacherName: '陈教授',
      selectTime: '2023-09-02 14:20:30'
    },
    {
      courseId: 'EN303',
      courseName: '英语写作',
      credit: 2,
      teacherName: '刘老师',
      selectTime: '2023-09-03 09:15:22'
    }
  ],
  '202102': [
    {
      courseId: 'CS101',
      courseName: '计算机科学导论',
      credit: 3,
      teacherName: '张教授',
      selectTime: '2023-09-01 11:42:18'
    },
    {
      courseId: 'AR404',
      courseName: '艺术设计',
      credit: 2,
      teacherName: '黄老师',
      selectTime: '2023-09-02 16:35:40'
    }
  ],
  '202103': [
    {
      courseId: 'CS101',
      courseName: '计算机科学导论',
      credit: 3,
      teacherName: '张教授',
      selectTime: '2023-09-01 09:22:33'
    },
    {
      courseId: 'MA202',
      courseName: '高等数学',
      credit: 4,
      teacherName: '陈教授',
      selectTime: '2023-09-01 10:15:21'
    },
    {
      courseId: 'PH505',
      courseName: '物理学',
      credit: 3,
      teacherName: '吴教授',
      selectTime: '2023-09-02 14:30:15'
    },
    {
      courseId: 'AR404',
      courseName: '艺术设计',
      credit: 2,
      teacherName: '黄老师',
      selectTime: '2023-09-03 16:40:25'
    }
  ]
}

// 功能标记 - 控制是否使用模拟数据
const USE_MOCK_DATA = true

// 获取学生分页列表
export function getStudentList(params) {
  if (USE_MOCK_DATA) {
    return new Promise((resolve) => {
      console.log('使用模拟学生数据')
      setTimeout(() => {
        // 过滤数据
        let filteredList = [...mockStudentList]
        
        if (params.keyword) {
          const keyword = params.keyword.toLowerCase()
          filteredList = filteredList.filter(item => 
            item.name.toLowerCase().includes(keyword) || 
            item.id.toLowerCase().includes(keyword) ||
            item.stuNo.toLowerCase().includes(keyword)
          )
        }
        
        if (params.grade) {
          filteredList = filteredList.filter(item => item.grade === params.grade)
        }
        
        if (params.major) {
          filteredList = filteredList.filter(item => item.major === params.major)
        }
        
        // 分页处理
        const total = filteredList.length
        const start = (params.page - 1) * params.pageSize
        const end = start + params.pageSize
        const list = filteredList.slice(start, end)
        
        resolve({
          status: 200,
          message: '获取成功',
          data: {
            list,
            total
          }
        })
      }, 500)
    })
  }
  
  return get('/student/pageQuery', params)
}

// 获取学生详情
export function getStudentDetail(id) {
  if (USE_MOCK_DATA) {
    return new Promise((resolve) => {
      console.log('使用模拟学生详情数据')
      setTimeout(() => {
        const student = mockStudentList.find(item => item.id === id)
        if (student) {
          resolve({
            status: 200,
            message: '获取成功',
            data: student
          })
        } else {
          resolve({
            status: 404,
            message: '学生不存在',
            data: null
          })
        }
      }, 300)
    })
  }
  
  return get(`/student/getById?id=${id}`)
}

// 新增/更新学生信息
export function saveOrUpdateStudent(data) {
  if (USE_MOCK_DATA) {
    return new Promise((resolve) => {
      console.log('保存模拟学生数据', data)
      setTimeout(() => {
        if (data.id) {
          // 更新
          const index = mockStudentList.findIndex(item => item.id === data.id)
          if (index !== -1) {
            mockStudentList[index] = { ...mockStudentList[index], ...data }
          }
        } else {
          // 新增
          const newId = `${new Date().getTime()}`
          const newStudent = {
            ...data,
            id: newId,
            courseCount: 0
          }
          mockStudentList.unshift(newStudent)
        }
        
        resolve({
          status: 200,
          message: '操作成功'
        })
      }, 500)
    })
  }
  
  return post('/student/saveOrUpdate', data)
}

// 删除学生
export function deleteStudent(id) {
  if (USE_MOCK_DATA) {
    return new Promise((resolve) => {
      console.log('删除模拟学生数据', id)
      setTimeout(() => {
        const index = mockStudentList.findIndex(item => item.id === id)
        if (index !== -1) {
          mockStudentList.splice(index, 1)
        }
        
        // 同时删除已选课程数据
        if (mockSelectedCourses[id]) {
          delete mockSelectedCourses[id]
        }
        
        resolve({
          status: 200,
          message: '删除成功'
        })
      }, 300)
    })
  }
  
  return del(`/student/delete?id=${id}`)
}

// 获取学生已选课程
export function getStudentCourses(studentId) {
  if (USE_MOCK_DATA) {
    return new Promise((resolve) => {
      console.log('获取模拟已选课程数据', studentId)
      setTimeout(() => {
        const courseList = mockSelectedCourses[studentId] || []
        resolve({
          status: 200,
          message: '获取成功',
          data: courseList
        })
      }, 300)
    })
  }
  
  return get('/student/courses', { studentId })
}

// 学生选课
export function selectCourse(data) {
  if (USE_MOCK_DATA) {
    return new Promise((resolve) => {
      console.log('模拟选课', data)
      setTimeout(() => {
        const { studentId, courseId } = data
        
        // 查找学生
        const student = mockStudentList.find(item => item.id === studentId)
        if (!student) {
          resolve({
            status: 400,
            message: '学生不存在'
          })
          return
        }
        
        // 查找课程
        const course = mockCourseList.find(item => item.courseId === courseId)
        if (!course) {
          resolve({
            status: 400,
            message: '课程不存在'
          })
          return
        }
        
        // 检查是否已满
        if (course.status === '已满') {
          resolve({
            status: 400,
            message: '课程已满'
          })
          return
        }
        
        // 检查是否已选
        const selectedCourses = mockSelectedCourses[studentId] || []
        if (selectedCourses.some(item => item.courseId === courseId)) {
          resolve({
            status: 400,
            message: '已选择该课程'
          })
          return
        }
        
        // 添加课程
        const newCourse = {
          courseId: course.courseId,
          courseName: course.courseName,
          credit: course.credit,
          teacherName: course.teacherName,
          selectTime: new Date().toLocaleString()
        }
        
        if (!mockSelectedCourses[studentId]) {
          mockSelectedCourses[studentId] = []
        }
        
        mockSelectedCourses[studentId].push(newCourse)
        
        // 更新学生选课数
        const studentIndex = mockStudentList.findIndex(item => item.id === studentId)
        if (studentIndex !== -1) {
          mockStudentList[studentIndex].courseCount = mockSelectedCourses[studentId].length
        }
        
        // 更新课程已选人数
        const courseIndex = mockCourseList.findIndex(item => item.courseId === courseId)
        if (courseIndex !== -1) {
          mockCourseList[courseIndex].selectedCount += 1
          
          // 判断是否已满
          if (mockCourseList[courseIndex].selectedCount >= mockCourseList[courseIndex].capacity) {
            mockCourseList[courseIndex].status = '已满'
          }
        }
        
        resolve({
          status: 200,
          message: '选课成功'
        })
      }, 500)
    })
  }
  
  return post('/student/selectCourse', data)
}

// 退选课程
export function cancelCourse(data) {
  if (USE_MOCK_DATA) {
    return new Promise((resolve) => {
      console.log('模拟退选课程', data)
      setTimeout(() => {
        const { studentId, courseId } = data
        
        // 检查是否已选
        if (!mockSelectedCourses[studentId] || !mockSelectedCourses[studentId].some(item => item.courseId === courseId)) {
          resolve({
            status: 400,
            message: '未选择该课程'
          })
          return
        }
        
        // 移除课程
        mockSelectedCourses[studentId] = mockSelectedCourses[studentId].filter(item => item.courseId !== courseId)
        
        // 更新学生选课数
        const studentIndex = mockStudentList.findIndex(item => item.id === studentId)
        if (studentIndex !== -1) {
          mockStudentList[studentIndex].courseCount = mockSelectedCourses[studentId].length
        }
        
        // 更新课程已选人数
        const courseIndex = mockCourseList.findIndex(item => item.courseId === courseId)
        if (courseIndex !== -1) {
          mockCourseList[courseIndex].selectedCount -= 1
          
          // 更新状态
          if (mockCourseList[courseIndex].status === '已满') {
            mockCourseList[courseIndex].status = '可选'
          }
        }
        
        resolve({
          status: 200,
          message: '退选成功'
        })
      }, 300)
    })
  }
  
  return del('/student/cancelCourse', data)
}

// 获取可选课程列表
export function getAvailableCourses(params) {
  if (USE_MOCK_DATA) {
    return new Promise((resolve) => {
      console.log('获取模拟可选课程列表', params)
      setTimeout(() => {
        let courseList = [...mockCourseList]
        
        // 关键词搜索
        if (params.keyword) {
          const keyword = params.keyword.toLowerCase()
          courseList = courseList.filter(course => 
            course.courseName.toLowerCase().includes(keyword) || 
            course.courseId.toLowerCase().includes(keyword) ||
            course.teacherName.toLowerCase().includes(keyword)
          )
        }
        
        resolve({
          status: 200,
          message: '获取成功',
          data: courseList
        })
      }, 300)
    })
  }
  
  return get('/student/availableCourses', params)
} 